package uno.rocc.common.exception;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import uno.rocc.common.constant.SecurityConstant;
import uno.rocc.common.util.Result;

import java.nio.file.AccessDeniedException;

@RestControllerAdvice
public class GlobalExceptionHandle {

    @ExceptionHandler(ServiceException.class)
    public Result handleServiceException(ServiceException e) {
        return Result.fail(e.errCode, e.getMessage());
    }

    @ExceptionHandler(AccessDeniedException.class)
    public Result handleAccessDeniedException(AccessDeniedException e) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return Result.fail(403, String.format(SecurityConstant.REQUEST_ACCESS_DENIED, requestAttributes.getRequest().getRequestURI()));
    }
}
